package net.huashitong.interceptor;

import huashitong.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 微信登录拦截器
 */
public class WeChatInterceptor extends HandlerInterceptorAdapter {
    Logger logger = LoggerFactory.getLogger(WeChatInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        logger.info("=========RequestURI================"+httpServletRequest.getRequestURI());
        String url = httpServletRequest.getRequestURI();
        url = URLEncoder.encode(url,"utf-8");
        Map<String,String[]> prmMap = httpServletRequest.getParameterMap();
        logger.info("=========prmMap================"+prmMap);

        if(prmMap != null){
            String parameters = "";
            for (String prm : prmMap.keySet()){
                parameters += "&" + prm + "=" + prmMap.get(prm)[0];
            }
            if(StringUtils.isNotBlank(parameters)){
                url = url + "?" + parameters.substring(1);
            }
        }

        logger.info("=="+url);
        httpServletResponse.sendRedirect(String.format( "%s/wechat/login?redirect_uri=%s",httpServletRequest.getContextPath(), url));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }



}
